package mytools;

import com.socks.library.KLog;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.LinkedList;

import gov.kqqzyyy.monkey.ydhl.R;

/**
 * Created by Monkey on 2017/11/7.
 * FTP类
 */

public class FtpUtil {

    static final String FTP_CONNECT_SUCCESSS = "ftp连接成功";
    static final String FTP_CONNECT_FAIL = "ftp连接失败";
    static final String FTP_DISCONNECT_SUCCESS = "ftp断开连接";
    static final String FTP_UPLOAD_SUCCESS = "ftp文件上传成功";
    static final String FTP_UPLOAD_FAIL = "ftp文件上传失败";
    static final String FTP_UPLOAD_LOADING = "ftp文件正在上传";

    private String hostName;
    private int serverPort;
    private String userName;
    private String password;
    private FTPClient ftpClient;

    public FtpUtil(String hostName, int serverPort, String userName, String password) {
        this.hostName = hostName;
        this.serverPort = serverPort;
        this.userName = userName;
        this.password = password;
        this.ftpClient = new FTPClient();
    }

    FtpUtil() {
        this.hostName = MyApplication.applicationContext.getString(R.string.default_ftp);
        this.serverPort = 21;
        this.userName = "ftpuser";
        this.password = "Ftp_123456";
        this.ftpClient = new FTPClient();
    }

    public void setHostName(String hostName) {
        this.hostName = hostName;
    }

    public void setServerPort(int serverPort) {
        this.serverPort = serverPort;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    //上传单个文件
    public void uploadSingleFile(File file, UploadListener listener, boolean delete) throws IOException {
        initBeforeUplaod(listener);
        boolean flag = doUpload(file, listener);
        if (flag) {
            listener.onUploadListener(FTP_UPLOAD_SUCCESS, 0, file);
            if (delete && file.exists()) {
                if (file.delete()) {
                    KLog.d("APE", "删除成功！");
                } else {
                    KLog.d("APE", "删除失败！");
                }
            }
        } else {
            listener.onUploadListener(FTP_UPLOAD_FAIL, 0, file);
        }
        closeAfterUpload(listener);
    }

    //多个文件上传
    void uploadMultiFile(LinkedList<File> fileList, UploadListener listener, boolean delete) throws IOException {
        initBeforeUplaod(listener);
        for (File singleFile : fileList
                ) {
            boolean flag = doUpload(singleFile, listener);
            if (flag) {
                listener.onUploadListener(FTP_UPLOAD_SUCCESS, 0, singleFile);
                if (delete && singleFile.exists()) {
                    if (singleFile.delete()) {
                        KLog.d("APE", "删除成功！");
                    } else {
                        KLog.d("APE", "删除失败！");
                    }
                }
            } else {
                listener.onUploadListener(FTP_UPLOAD_FAIL, 0, singleFile);
            }
        }
        closeAfterUpload(listener);
    }

    //上传（单个文件）
    private boolean doUpload(File file, UploadListener listener) {
        try {
            if (file.exists()) {
                BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
                ProgressInputStream progressInputStream = new ProgressInputStream(inputStream, listener, file);
                boolean flag = ftpClient.storeFile(file.getName(), progressInputStream);
                inputStream.close();
                return flag;
            } else {
                KLog.d("APE", "file not exist");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //初始化
    private void initBeforeUplaod(UploadListener listener) throws IOException {
        try {
            openConnect();
            listener.onUploadListener(FTP_CONNECT_SUCCESSS, 0, null);
        } catch (IOException e) {
            e.printStackTrace();
            listener.onUploadListener(FTP_CONNECT_FAIL, 0, null);
        }

    }

    //打开连接
    private void openConnect() throws IOException {
        int reply;
        ftpClient.connect(hostName, serverPort);
        reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
            KLog.d("APE", "connect fail: " + reply);
        } else {
            ftpClient.login(userName, password);
            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                KLog.d("APE", "login fail: " + reply);
            } else {
                FTPClientConfig config = new FTPClientConfig(ftpClient.getSystemType().split(" ")[0]);
                config.setServerLanguageCode("zh");
                ftpClient.configure(config);
                ftpClient.enterLocalPassiveMode();
                ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
                ftpClient.makeDirectory(NetWorkUtil.IPV4_ADD);
                ftpClient.changeWorkingDirectory(NetWorkUtil.IPV4_ADD);
            }
        }
    }

    //关闭连接
    private void closeConnect() {
        if (ftpClient != null && ftpClient.isConnected()) {
            try {
                // 退出FTP
                ftpClient.logout();
                // 断开连接
                ftpClient.disconnect();
            } catch (IOException e) {
                KLog.d("APE", e.getMessage());
                e.printStackTrace();
            }

        }
    }

    //上传完成关闭电脑
    private void closeAfterUpload(UploadListener listener)
            throws IOException {
        this.closeConnect();
        listener.onUploadListener(FTP_DISCONNECT_SUCCESS, 0, null);
    }
}
